// Copyright 2016 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Command svcmux reads a service interface XYZServer generated by protoc
// and generates VersionedXYZV struct that stores a map version->implementation,
// and a default version. Each method forwards a request to the implementation
// of the requested version.
//
// Example of usage:
// 	//go:generate svcmux -type GreetServer
package main

import (
	"context"
	"os"
	"strings"

	"go.chromium.org/luci/grpc/internal/svctool"
	"go.chromium.org/luci/grpc/svcmux"
)

func generate(c context.Context, a *svctool.GeneratorArgs) error {
	args := templateArgs{
		PackageName:        a.PackageName,
		VersionMetadataKey: svcmux.VersionMetadataKey,
		ExtraImports:       a.ExtraImports,
	}
	for _, svc := range a.Services {
		args.Services = append(args.Services, &service{
			Service:    svc,
			StructName: "Versioned" + strings.TrimSuffix(svc.TypeName, "Server"),
		})
	}

	// Execute template.
	return tmpl.Execute(a.Out, args)
}

func tool() *svctool.Tool {
	return &svctool.Tool{Name: "svcmux", OutputFilenameSuffix: "mux"}
}

func main() {
	tool().Main(os.Args[1:], generate)
}
